package cn.kgc.util;

import cn.hutool.json.JSONUtil;
import cn.kgc.entity.MessageInfo;
import cn.kgc.service.MessageInfoService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author YC
 * 发送消息的实体
 */
@Component
public class MessageInfoSender {

    @Value("${mq.serviceName}")
    private String serviceName;

    @Resource
    private MessageInfoService messageInfoService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 生产者发送正常信息
     */
    public void sendMessage(String exchange, String routingKey, Object message) {
        sendMessage(exchange, routingKey, message, 0);
    }

    /**
     * 生产者发送延迟信息
     */
    public void sendMessage(String exchange, String routingKey, Object message, long delay) {
        String jsonStr = JSONUtil.toJsonStr(message);
        // 发送信息前将信息保存在数据库中
        MessageInfo messageInfo = messageInfoService.messageSendReady(exchange, routingKey, jsonStr, serviceName, delay);
        // 发送信息到mq队列    header中的sequence是封装后的rabbitMessage发送次数 发送时传入信息ID以保证其唯一性
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType("application/json");
        // 向头中添加信息，回调时自己使用
        messageProperties.setHeader("sequence", messageInfo.getSequence());
        messageProperties.setHeader("delayTime", delay);
        // 设置rabbitMQ延迟时间
        messageProperties.setDelay(Math.toIntExact(delay));
        Message rabbitMessage = new Message(jsonStr.getBytes(StandardCharsets.UTF_8), messageProperties);
        rabbitTemplate.convertAndSend(exchange, routingKey, rabbitMessage, new CorrelationData(messageInfo.getId()));
    }

}
